package com.supermarket.service;

import com.supermarket.entity.OrderDelivery;
import com.supermarket.entity.Rider;
import com.supermarket.mapper.OrderDeliveryMapper;
import com.supermarket.mapper.RiderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 订单配送信息Service实现类
 */
@Service
public class OrderDeliveryService {

    @Autowired
    private OrderDeliveryMapper orderDeliveryMapper;
    
    @Autowired
    private RiderMapper riderMapper;

    /**
     * 创建订单配送信息
     * @param orderDelivery 配送信息
     * @return 是否成功
     */
    public boolean createOrderDelivery(OrderDelivery orderDelivery) {
        orderDelivery.setDeliveryStatus("PENDING"); // 默认待分配状态
        orderDelivery.setCreateTime(new Date());
        orderDelivery.setUpdateTime(new Date());
        return orderDeliveryMapper.insertOrderDelivery(orderDelivery) > 0;
    }
    
    /**
     * 根据ID查询配送信息
     * @param id 配送ID
     * @return 配送信息
     */
    public OrderDelivery getOrderDeliveryById(Integer id) {
        return orderDeliveryMapper.selectOrderDeliveryById(id);
    }
    
    /**
     * 根据订单ID查询配送信息
     * @param orderId 订单ID
     * @return 配送信息
     */
    public OrderDelivery getOrderDeliveryByOrderId(Integer orderId) {
        return orderDeliveryMapper.selectOrderDeliveryByOrderId(orderId);
    }
    
    /**
     * 根据骑手ID查询配送信息列表
     * @param riderId 骑手ID
     * @return 配送信息列表
     */
    public List<OrderDelivery> getOrderDeliveriesByRiderId(Integer riderId) {
        return orderDeliveryMapper.selectOrderDeliveriesByRiderId(riderId);
    }
    
    /**
     * 根据配送状态查询配送信息列表
     * @param deliveryStatus 配送状态
     * @return 配送信息列表
     */
    public List<OrderDelivery> getOrderDeliveriesByStatus(String deliveryStatus) {
        return orderDeliveryMapper.selectOrderDeliveriesByStatus(deliveryStatus);
    }
    
    /**
     * 查询骑手特定状态的配送信息
     * @param riderId 骑手ID
     * @param deliveryStatus 配送状态
     * @return 配送信息列表
     */
    public List<OrderDelivery> getOrderDeliveriesByRiderIdAndStatus(Integer riderId, String deliveryStatus) {
        return orderDeliveryMapper.selectOrderDeliveriesByRiderIdAndStatus(riderId, deliveryStatus);
    }
    
    /**
     * 分配骑手
     * @param deliveryId 配送ID
     * @param riderId 骑手ID
     * @return 是否成功
     */
    @Transactional
    public boolean assignRider(Integer deliveryId, Integer riderId) {
        Date now = new Date();
        OrderDelivery delivery = orderDeliveryMapper.selectOrderDeliveryById(deliveryId);
        Rider rider = riderMapper.selectRiderById(riderId);
        
        // 验证配送单和骑手状态
        if (delivery != null && "PENDING".equals(delivery.getDeliveryStatus()) 
                && rider != null && "AVAILABLE".equals(rider.getStatus())) {
            
            // 分配骑手
            int result = orderDeliveryMapper.assignRider(deliveryId, riderId, now);
            
            if (result > 0) {
                // 更新配送状态为已分配
                orderDeliveryMapper.updateDeliveryStatus(deliveryId, "ASSIGNED", now);
                
                // 更新骑手状态为配送中
                riderMapper.updateRiderStatus(riderId, "BUSY");
                
                return true;
            }
        }
        return false;
    }
    
    /**
     * 更新取件状态
     * @param deliveryId 配送ID
     * @return 是否成功
     */
    @Transactional
    public boolean updateToPickedStatus(Integer deliveryId) {
        Date now = new Date();
        OrderDelivery delivery = orderDeliveryMapper.selectOrderDeliveryById(deliveryId);
        
        // 验证配送单状态
        if (delivery != null && "ASSIGNED".equals(delivery.getDeliveryStatus())) {
            // 更新取件时间
            int result = orderDeliveryMapper.updatePickupTime(deliveryId, now);
            
            if (result > 0) {
                // 更新配送状态为已取件
                orderDeliveryMapper.updateDeliveryStatus(deliveryId, "PICKED", now);
                
                // 更新预计送达时间（当前时间 + 30分钟）
                Date estimatedTime = new Date(now.getTime() + 30 * 60 * 1000);
                orderDeliveryMapper.updateEstimatedDeliveryTime(deliveryId, estimatedTime);
                
                return true;
            }
        }
        return false;
    }
    
    /**
     * 更新送达状态
     * @param deliveryId 配送ID
     * @return 是否成功
     */
    @Transactional
    public boolean updateToDeliveredStatus(Integer deliveryId) {
        Date now = new Date();
        OrderDelivery delivery = orderDeliveryMapper.selectOrderDeliveryById(deliveryId);
        
        // 验证配送单状态
        if (delivery != null && "PICKED".equals(delivery.getDeliveryStatus())) {
            // 更新实际送达时间
            int result = orderDeliveryMapper.updateActualDeliveryTime(deliveryId, now);
            
            if (result > 0) {
                // 更新配送状态为已送达
                orderDeliveryMapper.updateDeliveryStatus(deliveryId, "DELIVERED", now);
                
                // 更新骑手状态为可接单
                if (delivery.getRiderId() != null) {
                    // 增加骑手配送单数
                    riderMapper.incrementDeliveryCount(delivery.getRiderId());
                    // 更新骑手状态
                    riderMapper.updateRiderStatus(delivery.getRiderId(), "AVAILABLE");
                }
                
                return true;
            }
        }
        return false;
    }
    
    /**
     * 评价骑手
     * @param deliveryId 配送ID
     * @param rating 评分（1-5分）
     * @param comment 评价内容
     * @return 是否成功
     */
    @Transactional
    public boolean rateRider(Integer deliveryId, Integer rating, String comment) {
        OrderDelivery delivery = orderDeliveryMapper.selectOrderDeliveryById(deliveryId);
        
        // 验证配送单状态和评分范围
        if (delivery != null && "DELIVERED".equals(delivery.getDeliveryStatus()) 
                && rating >= 1 && rating <= 5) {
            
            // 添加评价
            int result = orderDeliveryMapper.rateRider(deliveryId, rating, comment);
            
            if (result > 0 && delivery.getRiderId() != null) {
                // 获取骑手所有评分并计算平均值
                List<OrderDelivery> deliveries = orderDeliveryMapper.selectOrderDeliveriesByRiderId(delivery.getRiderId());
                double totalRating = 0;
                int ratingCount = 0;
                
                for (OrderDelivery d : deliveries) {
                    if (d.getRiderRating() != null) {
                        totalRating += d.getRiderRating();
                        ratingCount++;
                    }
                }
                
                if (ratingCount > 0) {
                    // 计算新的平均评分
                    double avgRating = totalRating / ratingCount;
                    // 更新骑手评分
                    riderMapper.updateRiderRating(delivery.getRiderId(), new java.math.BigDecimal(avgRating));
                }
                
                return true;
            }
        }
        return false;
    }
    
    /**
     * 更新配送信息
     * @param orderDelivery 配送信息
     * @return 是否成功
     */
    public boolean updateOrderDelivery(OrderDelivery orderDelivery) {
        orderDelivery.setUpdateTime(new Date());
        return orderDeliveryMapper.updateOrderDelivery(orderDelivery) > 0;
    }

    /**
     * 骑手领取订单（将订单分配给骑手）
     *
     * @param deliveryId 配送ID
     * @param riderId 骑手ID
     * @return 是否成功
     */
    public boolean assignDeliveryToRider(Integer deliveryId, Integer riderId) {
        OrderDelivery delivery = getOrderDeliveryById(deliveryId);
        
        // 验证订单状态，只有PENDING状态的订单可以被领取
        if (delivery == null || !"PENDING".equals(delivery.getDeliveryStatus())) {
            return false;
        }
        
        // 更新状态为已分配
        delivery.setRiderId(riderId);
        delivery.setDeliveryStatus("ASSIGNED");
        delivery.setUpdateTime(new Date());
        
        // 更新骑手状态为忙碌（如果当前是在线状态）
        Rider rider = riderMapper.selectRiderById(riderId);
        if (rider != null && "AVAILABLE".equals(rider.getStatus())) {
            riderMapper.updateRiderStatus(riderId, "BUSY");
        }
        
        return orderDeliveryMapper.updateOrderDelivery(delivery) > 0;
    }
} 